using FluentNHibernate.Cfg;
using NHibernate;
using Wikey.Extensibility.Interfaces;

namespace Wikey.Domain.Components
{
    public interface ISessionSource {
        ISession CreateSession();
        void Close();
        void BuildSchema();
    }

    public class SessionSource : FluentNHibernate.SessionSource, ISessionSource {

        private ISession CurrentSession;
        public SessionSource(FluentConfiguration config) : base(config) { }
        static readonly object padlock = new object();

        public override ISession CreateSession() {

            if (CurrentSession == null || !CurrentSession.IsOpen) {

                lock (padlock)
                {
                    CurrentSession = base.CreateSession();
                    Factory.Get<ILogger>().Debug("Recreate the session called " + CurrentSession.ToString());
                }
                
            }
            else
            {
                Factory.Get<ILogger>().Debug("No need to create the current session" + CurrentSession.ToString());
            }
            return CurrentSession;
        }

        public void Close() {
            if (CurrentSession != null) {
                lock(padlock)
                {
                    if(CurrentSession!=null)
                        CurrentSession.Dispose();

                    Factory.Get<ILogger>().Debug("Session Source Close called");                                       
                }
            }
            else
            {
                Factory.Get<ILogger>().Debug("Current session is already dead" );
            }
        }

    }
}